#!/usr/bin/env bash
##
# Update/copy necessary files to bios path for Guix system due
# it donesn't support /boot partition by default
# from: https://issues.guix.gnu.org/48172
##
set -e
prefix="$1"

# Copy kernel and initrd images to /boot
images=$(grep -E '^  (linux|initrd) ' $prefix/boot/grub/grub.cfg \
             | awk '{ print $2 }' | sed 's|.*/gnu|/gnu|g' | sort | uniq)

for image in $images; do
    mkdir -p $prefix/boot$(dirname $image)
    if [ ! -e $prefix/boot$image ] || ! cmp -s $prefix$image $prefix/boot$image; then
        echo copying cp $prefix$image to $preifx/boot$image... > /dev/error
        cp $prefix$image $prefix/boot$image
    fi
done

# Adjust /boot/grub/grub.cfg.
sed -E -e 's/.*search.*--set.*//' \
    -e 's/^insmod luks.*//' \
    -e 's/^cryptomount.*//' \
    -e 's,^(  (linux|initrd) )[^ ]*(/gnu/[^ ]* ?),\1\3,' \
    -i.bak $prefix/boot/grub/grub.cfg
